package com.iscc.maoke.controller;

import com.google.gson.Gson;
import com.iscc.maoke.domain.Img;
import com.iscc.maoke.domain.Product;
import com.iscc.maoke.service.ProductService;
import com.iscc.maoke.service.impl.ProductServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/add_product.do")
public class ProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        Gson gson = new Gson();
        Map<String, Object> resultMap = new HashMap<>();

        ProductService productService = new ProductServiceImpl();
        //创建一个DiskFileItemFactory对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //获取一个上传对象
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置编码格式
        upload.setHeaderEncoding("UTF-8");


        try {
            //将请求对象转换为List集合
            List<FileItem> items = upload.parseRequest(request);

            Product product = new Product();


            //获取根路径的物理路径
            String path = this.getServletContext().getRealPath("upload");
            File uploadFile = new File(path);
            //判断目录是否存在，不存在创建
            if (!uploadFile.exists()) {
                uploadFile.mkdirs();
                //mkdir(), mkdirs()
            }

            List<DiskFileItem> dList = new ArrayList<>();

            for (FileItem item : items) {
                //如果是正常的表单字段
                if (item.isFormField()) {
                    String val = new String(item.getString().getBytes("iso-8859-1"), "UTF-8");
                    if ("prodName".equals(item.getFieldName())) {
                        product.setPname(val);
                    } else if ("prodType".equals(item.getFieldName())) {
                        product.setTno(Integer.parseInt(val));
                    } else if ("prodPrice".equals(item.getFieldName())) {
                        product.setPrice(Double.parseDouble(val));
                    } else if ("prodDiscount".equals(item.getFieldName())) {
                        product.setDiscount(Double.parseDouble(val));
                    } else if ("prodSummary".equals(item.getFieldName())) {
                        product.setSummary(val);
                    }
                } else {
                    DiskFileItem fileItem = (DiskFileItem) item;
                    if ("prodCover".equals(item.getFieldName())) {
                        File coverFile = new File(uploadFile, fileItem.getName());
                        fileItem.write(coverFile);
                        product.setCover("/upload/" + coverFile.getName());
                    } else {
                        System.out.println("fileItem = " + fileItem);
                        dList.add(fileItem);
                    }
                }
            }

            List<Img> imgs = new ArrayList<>();
            for (DiskFileItem fileItem : dList) {
                System.out.println(":::::::::::::::" + fileItem.getName());
                Img img = new Img("/upload/" + fileItem.getName());

                imgs.add(img);
                File tempFile = new File(uploadFile, fileItem.getName());
                fileItem.write(tempFile);

            }


            int result = productService.addProduct(product, imgs);

            if (result != -1) {
                resultMap.put("code", 200);
                resultMap.put("msg", "发布商品成功");
            } else {
                resultMap.put("code", 201);
                resultMap.put("msg", "发布商品失败");
            }

            response.getWriter().print(gson.toJson(resultMap));

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
